package cn.gx.learn.security_boot_jwt_websocket.base.service.mail;


import cn.gx.learn.security_boot_jwt_websocket.base.dal.database.EmailMessage;
import cn.gx.learn.security_boot_jwt_websocket.base.dal.mysql.EmailMessageMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EmailServiceImpl extends ServiceImpl<EmailMessageMapper, EmailMessage> implements EmailService{

    @Autowired
    private JavaMailSender mailSender;

    @Value("${admin.email}")
    private String adminEmail;

    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 发送简单邮件
     */
    public void sendSimpleEmail(EmailMessage emailMessage) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(emailMessage.getReceiver());
            message.setSubject(emailMessage.getSubject());
            message.setText(emailMessage.getContent());
            message.setFrom(sender); // 发送方邮箱

            mailSender.send(message);
            log.info("邮件发送成功，收件人：{}，主题：{}", emailMessage.getReceiver(), emailMessage.getSubject());
        } catch (Exception e) {
            log.error("邮件发送失败：{}", e.getMessage(), e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 发送预约通知邮件
     */
    public void sendAppointmentNotificationEmail(Long appointmentId, String userName, String appointmentDetails) {
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.setReceiver(adminEmail);
        emailMessage.setSubject("新预约通知 - " + userName);
        emailMessage.setContent(buildAppointmentEmailContent(userName, appointmentDetails));
        emailMessage.setEmailType("APPOINTMENT_NOTIFICATION");
        emailMessage.setAppointmentId(appointmentId);
        emailMessage.setUserName(userName);

        sendSimpleEmail(emailMessage);
    }

    /**
     * 构建预约邮件内容
     */
    private String buildAppointmentEmailContent(String userName, String appointmentDetails) {
        StringBuilder content = new StringBuilder();
        content.append("您好！\n\n");
        content.append("您有一个新的预约申请：\n\n");
        content.append("用户姓名：").append(userName).append("\n");
        content.append("预约详情：").append(appointmentDetails).append("\n\n");
        content.append("请及时处理此预约申请。\n\n");
        content.append("此邮件由系统自动发送，请勿回复。");

        return content.toString();
    }

}
